<?php

include_once '../inc/db_util.php';

function viewPost($filter) {
    $array_post = array();
    $jsArray = json_decode($filter, false);
    $query = mysql_query("SELECT tp.*, `user`.* FROM tb_posting tp
             JOIN tb_thread tr ON tp.id_thread = tr.id_thread
             JOIN (
                SELECT nip id, namadosen nama, username FROM tb_dosen
                UNION                            
                SELECT id_mahasiswa id, nama, username FROM tb_mahasiswa
             ) user ON tp.id_user_post = user.id
             WHERE tr.id_thread = '" . $jsArray->{'Id'} . "'
             ORDER BY tp.tanggal_create
             ");

    while ($row = mysql_fetch_array($query, MYSQL_BOTH)) {
        $row_array['Id'] = $row['id_posting'];
        $row_array['Comment'] = $row['komen'];
        $row_array['Created'] = $row['tanggal_create'];
        $row_array['Sender']['Id'] = $row['id'];
        $row_array['Sender']['Username'] = $row['username'];
        $row_array['Sender']['Nama'] = substr($row['nama'], 0, 15);
        $row_array['Forum']['Id'] = $row['id_thread'];

        array_push($array_post, $row_array);
    }
    return json_encode($array_post);
}

function addPost($json) {
    $jsArray = json_decode($json, false);

    $sql = "INSERT INTO tb_posting(id_thread, id_user_post, komen, tanggal_create, username)
        VALUES (            
        '" . $jsArray->{'Forum'}->{'Id'} . "',
        '" . $jsArray->{'Sender'}->{'Id'} . "',
        '" . $jsArray->{'Comment'} . "',
        NOW(), 
        '" . $jsArray->{'Sender'}->{'Username'} . "'
        )";
    return mysql_query($sql);
}

function updatePost($json) {
    $jsArray = json_decode($json, false);
    $sql = "UPDATE tb_posting SET
        komen = '" . $jsArray->{'Comment'} . "'
        WHERE id_posting = '" . $jsArray->{'Id'} . "'";

    return mysql_query($sql);
}

function deletePost($json) {
    $jsArray = json_decode($json, false);
    $sql = "DELETE FROM tb_posting WHERE id_posting = '" . $jsArray->{'Id'} . "'";
	
	return mysql_query($sql);
}

?>
